<template>
  <view class="volunteer">
    <global-nav-bar title="加入志愿者"/>
    <view class="container">
      <uv-form labelPosition="left" :model="formData" :rules="rules" ref="form">
        <uv-form-item label="姓名" prop="formData.username" borderBottom required>
          <uv-input v-model="formData.username" border="none" placeholder="请输入姓名"/>
        </uv-form-item>
        <uv-form-item label="年龄" prop="formData.age" borderBottom required>
          <uv-input v-model="formData.age" border="none" placeholder="请输入年龄"/>
        </uv-form-item>
        <uv-form-item label="电话" prop="formData.mobile" borderBottom required>
          <uv-input v-model="formData.mobile" border="none" placeholder="请输入联系电话"/>
        </uv-form-item>
        <uv-form-item label="邮箱" prop="formData.email" borderBottom>
          <uv-input v-model="formData.email" border="none" placeholder="请输入邮箱"/>
        </uv-form-item>
        <uv-form-item label="身份证号" labelWidth="140rpx" prop="formData.user_num" borderBottom
                      required>
          <uv-input v-model="formData.user_num" border="none" placeholder="请输入身份证号"/>
        </uv-form-item>
        <uv-form-item label="家庭住址" labelWidth="140rpx" prop="formData.address" borderBottom
                      required>
          <uv-input v-model="formData.address" border="none" placeholder="请输入家庭住址"/>
        </uv-form-item>
        <uv-form-item label="性别" prop="formData.sex" borderBottom required>
          <uv-radio-group v-model="formData.sex" placement="row">
            <uv-radio v-for="(v, k) in sex" :name="k" :label="v"
                      :customStyle="{padding: '0 10px'}"/>
          </uv-radio-group>
        </uv-form-item>
        <uv-form-item label="是否有犯罪记录" labelWidth="250rpx" prop="formData.sex" borderBottom
                      required>
          <uv-radio-group v-model="formData.is_fanzui" placement="row">
            <uv-radio v-for="(v, k) in is_fanzui" :name="k" :label="v"
                      :customStyle="{padding: '0 10px'}"/>
          </uv-radio-group>
        </uv-form-item>
        <uv-form-item label="身体状况" labelWidth="140rpx" prop="formData.sex" borderBottom
                      required>
          <uv-radio-group v-model="formData.body_status" placement="row">
            <uv-radio v-for="(v, k) in body_status" :name="k" :label="v"
                      :customStyle="{padding: '0 10px'}"/>
          </uv-radio-group>
        </uv-form-item>
        <uv-form-item label="是否服从馆方安排" labelWidth="260rpx" prop="formData.sex" borderBottom
                      required>
          <uv-radio-group v-model="formData.is_fucong" placement="row">
            <uv-radio v-for="(v, k) in is_fucong" :name="k" :label="v"
                      :customStyle="{padding: '0 10px'}"/>
          </uv-radio-group>
        </uv-form-item>
        <uv-form-item label="民族" prop="formData.minzu" borderBottom @click="toggleEnhnic"
                      required>
          <uv-input v-model="formData.minzu" disabled disabledColor="#ffffff"
                    placeholder="请选择民族"
                    border="none"/>
          <template v-slot:right>
            <uv-icon name="arrow-right"></uv-icon>
          </template>
        </uv-form-item>
        <uv-form-item label="政治面貌" prop="formData.minzu" labelWidth="140rpx" borderBottom
                      @click="toggleEnhnic" required labelPosition="top">
          <uv-radio-group v-model="formData.zhengzhi" placement="row">
            <uv-radio v-for="(v, k) in zhengzhi" :name="k" :label="v"
                      :customStyle="{padding: '10px'}"/>
          </uv-radio-group>
        </uv-form-item>
        <uv-form-item label="学历" prop="formData.minzu" labelWidth="140rpx" borderBottom
                      @click="toggleEnhnic" required labelPosition="top">
          <uv-radio-group v-model="formData.school_level" placement="row">
            <uv-radio v-for="(v, k) in school_level" :name="k" :label="v"
                      :customStyle="{padding: '10px'}"/>
          </uv-radio-group>
        </uv-form-item>
        <uv-form-item label="一寸免冠照片" prop="formData.minzu" labelWidth="200rpx" borderBottom
                      @click="toggleEnhnic" required>
          <uv-upload
            :fileList="fileList1"
            name="1"

			:previewFullImage="true"
					@afterRead="afterRead" 
					@delete="deletePic" 
          />
        </uv-form-item>
        <view class="studyAndWorkExperience">
          <view class="row1">
            <view class="title">学习及工作经历</view>
            <uv-icon name="plus-circle" size="20" @click="addStudy"></uv-icon>
          </view>
          <view class="row2">
            <view class="item" v-for="(item, index) in formData.work_list" :key="index">
              <uv-form-item label="时间" labelWidth="140rpx" prop="formData.sex">
                <view class="time">
                  <view @click="selectStartDatePicker(index)">
                    <uv-input v-model="formData.work_list[index].name1" disabled
                              disabledColor="#eee"
                              placeholder="开始日期" border="none"
                    />
                  </view>
                  至
                  <view @click="selectEndDatePicker(index)">
                    <uv-input v-model="formData.work_list[index].name2" disabled
                              disabledColor="#eee"
                              placeholder="结束日期" border="none"
                    />
                  </view>
                </view>
                <uv-datetime-picker :ref="`startDatePicker${index}`" mode="year"
                                    :formatter="formatter"
                                    @confirm="(e) => selectStartDateConfirm(e, index)"/>
                <uv-datetime-picker :ref="'endDatePicker' + index" mode="year"
                                    :formatter="formatter"
                                    @confirm="(e) => selectEndDateConfirm(e, index)"/>
              </uv-form-item>
              <uv-form-item label="经历" labelWidth="140rpx" prop="formData.sex">
                <uv-input v-model="formData.work_list[index].name3" border="none"
                          :customStyle="inputCustomStyle"
                          placeholder="请输入学习及工作经历"/>
              </uv-form-item>
              <uv-form-item label="职务职称" labelWidth="140rpx" prop="formData.sex">
                <uv-input v-model="formData.work_list[index].name4" border="none"
                          placeholder="请输入职务支撑"
                          :customStyle="inputCustomStyle"/>
              </uv-form-item>
            </view>
          </view>
        </view>
        <uv-form-item label="意向服务时间" labelPosition="top" labelWidth="200rpx" required
                      borderBottom>
          <view class="intentServiceTime">
            <uv-radio-group v-model="formData.join_type" @change="serviceHours">
              <uv-radio name="1" label="通用时间" :customStyle="{padding:'10px'}"/>
              <uv-radio name="2" label="自定义时间" :customStyle="{padding:'10px'}"/>
            </uv-radio-group>
            <view v-if="formData.join_type === '1'" class="box1">
              <uv-checkbox-group v-model="ccommon_data" placement="row">
                <uv-checkbox
                  :customStyle="{margin: '10px'}"
                  v-for="(item, index) in common_date"
                  :key="index" :label="item.name"
                  :name="item.value"
                />
              </uv-checkbox-group>
            </view>
            <view v-else class="box2">
              <view class="calenderList">
                <view class="item" v-for="(item, index) in calenderList">
                  <text>{{ item }}</text>
                  <uv-icon name="trash" size="20" @click="delCalender(index)"></uv-icon>
                </view>
              </view>

            </view>
          </view>
        </uv-form-item>

        <uv-button type="primary" text="申请成为志愿者" customStyle="margin-top: 10px"
                   @click="submit"></uv-button>
      </uv-form>
    </view>
    <uv-action-sheet ref="sexSelect" :actions="actions" title="请选择性别" @select="sexSelect">
    </uv-action-sheet>
    <uv-picker ref="ethnic" :columns="ethnic" @confirm="toggleEnhnic"></uv-picker>

    <uv-calendar ref="calendar" mode="multiple" @confirm="selectCalenderConfirm"/>
  </view>
</template>

<script>
	import http from '@/utils/request.js'
	
// 姓名 性别 犯罪记录 身体状况 是否服从馆方安排 民族 年龄 政治面貌 联系电话 邮箱 学历 毕业院校（系）专业 身份证号 家庭住址 免冠照片 学习及工作经历 意向服务时间 通用时间 自定义时间
export default {
  data() {
    return {
		fileList1:[],
      inputCustomStyle: {background: '#eee'},
      formData: {
		  email:'',
		user_num:'',
        username: '',
        sex: '1',
        minzu: '',
        is_fanzui: '2',
        body_status: '1',
        is_fucong: '1',
        zhengzhi: '',
        school_level: '',
        minzu: '',
        join_type: '1',
        time_value: '',
		address:'',
        work_list: [{name1: '', name2: '', name3: '', name4: ''}]
      },
      rules: {
        username: {
          type: 'string',
          required: true,
          message: '请输入姓名',
          trigger: ['blur', 'change']
        },
      },
      sex: {},
      is_fanzui: {},
      body_status: {},
      is_fucong: {},
      zhengzhi: {},
      school_level: {},
      ethnic: [],
      calenderList: [],
      common_date: [],
      ccommon_data: []
    };
  },
  onLoad() {
    this.getPackage()
  },
  methods: {
    async getPackage() {
      const res = await this.$http.post('/api/Volunteer/config')
      console.log(res.data)
      if (res.code !== 1) return console.warn(res)
      this.ethnic.push(res.data.minzu)
      this.sex = res.data.sex
      this.is_fanzui = res.data.is_fanzui
      this.body_status = res.data.body_status
      this.is_fucong = res.data.is_fucong
      this.zhengzhi = res.data.zhengzhi
      this.school_level = res.data.school_level
      this.common_date = res.data.common_date
    },
    addStudy() {
      this.formData.work_list.push({name1: '', name2: '', name3: '', name4: ''})
    },
    // 性别选择
    showSexSelect() {
      this.$refs.sexSelect.open();
      this.hideKeyboard();
    },
    // 性别选择返回结果
    sexSelect(e) {
      this.formData.sex = e.name;

    },
    // 提交
    submit() {
		 if(!this.formData.username){
			uni.showToast({
				icon:'error',
				'title':'请输入姓名',
			})
			return false;
		}
		if(!this.formData.age){
			uni.showToast({
				icon:'error',
				'title':'请输入年龄',
			})
			return false;
		}
		if(!this.formData.mobile){
			uni.showToast({
				icon:'error',
				'title':'请输入手机号',
			})
			return false;
		}
		if(!this.formData.user_num){
			uni.showToast({
				icon:'error',
				'title':'请输入身份证号',
			})
			return false;
		}
		if(!this.formData.address){
			uni.showToast({
				icon:'error',
				'title':'请输入住址',
			})
			return false;
		}
		if(!this.formData.minzu){
			uni.showToast({
				icon:'error',
				'title':'请输入民族',
			})
			return false;
		}
		if(!this.formData.zhengzhi){
			uni.showToast({
				icon:'error',
				'title':'请输入政治面貌',
			})
			return false;
		}
		if(!this.formData.school_level){
			uni.showToast({
				icon:'error',
				'title':'请输入学历',
			})
			return false;
		}
		if(this.fileList1[0]){
			this.formData['head_image'] = JSON.parse(this.fileList1[0].url).data.url;	  
		}else{
			uni.showToast({
				icon:'error',
				'title':'请上传图片',
			})
			return false;
		}
		if(this.formData.work_list){
			this.formData.work_listjson = JSON.stringify(this.formData.work_list);
		}
		
		if(this.formData.join_type == 1){
			this.formData['time_value'] = this.ccommon_data.join(',');
		}else{
			this.formData['time_value'] = this.calenderList.join(',');
		} 
		http.post('api/volunteer/submit',this.formData).then(function(data){
			if(data.code == 1){
				uni.showToast({
					icon:'success',
					'title':'报名成功',
				})
				setTimeout(function(){
					uni.switchTab({
						url:'/pages/index/index'
					})
				},2000)
			}else{
				uni.showToast({
					icon:'error',
					title:'报名失败',
				})
			}
		})
    },
    // 打开民族选择器
    toggleEnhnic(e) {
      if (!e) {
        this.$refs.ethnic.open()
      } else {
        console.log('confirm', e);
        this.formData.minzu = e.value[0]
      }
    },
    // 选择开始日期
    selectStartDatePicker(index) {
      this.$refs[`startDatePicker${index}`][0].open()
    },
    selectStartDateConfirm(e, index) {
      this.formData.work_list[index].name1 = new Date(e.value).getFullYear()
      // this.formData.work_list[index].name1 = this.$utils.timestampToTime(e.value)
    },
    // 选择结束日期
    selectEndDatePicker(index) {
      this.$refs['endDatePicker' + index][0].open()
    },
    selectEndDateConfirm(e, index) {
      this.formData.work_list[index].name2 = new Date(e.value).getFullYear()
      // this.formData.work_list[index].name2 = this.$utils.timestampToTime(e.value)
    },
    serviceHours(e) {
      if (Number(e) === 2) {
        this.$refs.calendar.open()
      }
    },
    // 选择日期
    selectCalenderConfirm(e) {
      this.calenderList = e
    },
    delCalender(index) {
      this.calenderList.splice(index, 1)
    },
	// 删除图片
		deletePic(event) {
			this[`fileList1`].splice(event.index, 1)
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file)
			let fileListLen = this[`fileList1`].length
			lists.map((item) => {
				this[`fileList1`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				})
			})
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url)
				let item = this[`fileList1`][fileListLen]
				this[`fileList1`].splice(fileListLen, 1, Object.assign(item, {
					status: 'success',
					message: '',
					url: result
				}))
				fileListLen++
			}
		},
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: http.common.baseUrl+'api/common/upload', // 仅为示例，非真实的接口地址
					filePath: url,
					name: 'file',
					formData: {
					
					},
					header: {
						'token': uni.getStorageSync('token') // 设置认证token
					 },
					success: (res) => {
						setTimeout(() => {
							resolve(res.data)
						}, 1000)
					}
				});
			})
		}
  }
}
</script>

<style lang="scss" scoped>
.volunteer {
  width: calc(100% - 60rpx);
  padding: 30rpx 30rpx 0;

  .container {
    padding-bottom: calc(40rpx + var(--window-bottom));
  }

  .studyAndWorkExperience {
    width: 100%;
    border-bottom: 1rpx solid #d6d7d9;

    .row1 {
      width: 100%;
      padding: 40rpx 0 20rpx 0;
      border-bottom: 1rpx solid #d6d7d9;
      @include flex(row, space-between, center);

      .title {
        font-size: 30rpx;
      }
    }

    .row2 {
      width: calc(100% - 30rpx);
      padding-left: 30rpx;

      .item {
        width: 100%;
        padding-bottom: 20rpx;

        &:not(:last-child) {
          border-bottom: 1px solid #d6d7d9;
        }

        /deep/ .time {
          width: 100%;
          @include flex(row, space-between, center);
        }
      }
    }
  }

  .intentServiceTime {
    .box1 {

    }

    .box2 {
      .calenderList {
        width: 100%;
        @include flex(row, flex-start, center);
        flex-wrap: wrap;

        .item {
          margin: 10rpx;
          padding: 10rpx;
          border: 1px solid #eee;
          @include flex(row, center, center);

          text {
            margin-right: 20rpx;
          }
        }
      }
    }
  }
}
</style>
